﻿using Sustainalytics.DataLayer.Shared;
using Sustainalytics.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using MongoDB.Driver.Linq;
using MongoDB.Driver;

namespace Sustainalytics.DataLayer
{
    public class FilterCriteriaRepository : RepositoryCollection<FilterCriteria>, IFilterCriteriaRepository
    {
        public FilterCriteriaRepository(string cnxString)
            : base(cnxString)
        {           
        }

        public FilterCriteria GetFilterCriteriaById(Guid filterCriteriaId)
        {
            return this.Read(filterCriteriaId);
        }

        public List<FilterCriteria> GetAllFilterCriteriaByFilterId(Guid filterId)
        {
            if (filterId == null)
                throw new ArgumentNullException();

            var query = this.Collection().AsQueryable()
                .Where(x => x.FilterId == filterId)
                .OrderBy(x => x.Order);

            return query.ToList();
        }

        public List<FilterCriteria> GetFilterCriteriaGroupByFilterGroupId(Guid filterGroupId)
        {
            return this.ReadAllWhere(x => x.FilterGroupId == filterGroupId).ToList();
        }

        public List<FilterCriteria> GetFilterCriteriaGroup(Guid filterId, Guid criteriaLevel2Id, Guid criteriaLevel3Id)
        {
            return this.ReadAllWhere(x => x.FilterId == filterId && x.CriteriaLevel2Id == criteriaLevel2Id && x.CriteriaLevel3Id == criteriaLevel3Id).ToList();
        }

        public void DeleteFilterCriteria(Guid criteriaId)
        {
            this.Delete(criteriaId);
        }

        public void DeleteAllFilterCriteriaByFilterId(Guid filterId)
        {
            this.Collection().DeleteMany(Builders<FilterCriteria>.Filter.Where(c => c.FilterId == filterId));
        }

        public void DeleteFilterCriteriaByIdTemplateIdAndFilterId(Guid templateCriteriaId, Guid filterId)
        {
            this.DeleteWhere(x => x.TemplateCriteriaId == templateCriteriaId && x.FilterId == filterId);
        }

        public void DeleteFilterCriteriaByFilterGroupId(Guid filterId, Guid filterGroupId)
        {
            this.DeleteWhere(x => x.FilterId == filterId && x.FilterGroupId == filterGroupId);
        }
    }
}
